import time
import logging
import threading

class TaskScheduler:
    def __init__(self):
        self.task_thread = None
        self.running = False
        self.interval = 0
        self.task_function = None

    def start_interval_task(self, interval, task_function):
        """启动间隔任务（在独立线程中执行）"""
        if self.running:
            logging.warning("任务已在运行中")
            return

        self.interval = interval
        self.task_function = task_function
        self.running = True

        # 创建并启动后台线程（daemon=True确保程序退出时线程自动终止）
        self.task_thread = threading.Thread(target=self._task_loop, daemon=True)
        self.task_thread.start()
        logging.info(f"任务线程启动，间隔{interval}秒")

    def _task_loop(self):
        """任务循环（在独立线程中运行）"""
        while self.running:
            start_time = time.time()

            try:
                if self.task_function and self.running:  # 双重检查确保任务可执行
                    self.task_function()  # 调用实际任务
            except Exception as e:
                logging.error(f"任务执行异常: {str(e)}")
                # 异常不中断循环，继续下一次执行

            # 计算剩余等待时间（确保间隔准确，不受任务执行时间影响）
            elapsed = time.time() - start_time
            wait_time = max(0, self.interval - int(elapsed))

            # 分段等待，确保能及时响应stop()
            while wait_time > 0 and self.running:
                sleep_time = min(0.5, wait_time)  # 最多等待0.5秒就检查一次状态
                time.sleep(sleep_time)
                wait_time -= sleep_time

    def stop(self):
        """安全停止任务线程，确保不抛出异常"""
        try:
            if self.running:
                self.running = False
                # 等待线程结束，设置超时时间
                if self.task_thread and self.task_thread.is_alive():
                    self.task_thread.join(timeout=2.0)  # 最多等待2秒
                self.task_thread = None
        except Exception as e:
            # 静默处理停止时的异常
            pass
